package com.coder.rental.security;

import com.coder.rental.entity.Permission;
import com.coder.rental.entity.User;
import com.coder.rental.service.IPermissionService;
import com.coder.rental.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 该实现类被用来从某个持久化存储（例如数据库、LDAP服务器等）中检索用户的具体信息。
 * 查询用户信息 用户权限列表 用户子权限 并封装用户
 */
@Component
public class CustomerUserDetailService implements UserDetailsService {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private IPermissionService iPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=iUserService.selectByUsername(username); //到数据库中按username去查询
        if (user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //查询用户的权限列表,并封装到用户对象中去
        List<Permission> permissionList = iPermissionService.selectPermissionListByUserId(user.getId());
        user.setPermissionList(permissionList);
        //通过stream流处理,将权限对象转换为权限
//        permissionList.stream().filter(permission -> permission.getPermissionCode()!=null);
        List<String> list = permissionList.stream().filter(Objects::nonNull)
                .map(Permission::getPermissionCode)
                .filter(Objects::nonNull)
                .toList();

        String[] array = list.toArray(new String[list.size()]);
        //子权限的封装
        List<GrantedAuthority> authorityList= AuthorityUtils.createAuthorityList(array);
        user.setAuthorities(authorityList);
        return user;
    }
}